﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TVShow.Framework
{
	public class TVSMessage
	{
		static List<IPlugin> Plugins = new List<IPlugin>();

		public delegate void MessageEventHandler(TVSMessage sender);
		/// <summary>
		/// Process a message after everything else has had the chance.
		/// This primarily lets the main window shut down cleanly.
		/// </summary>
		public static event MessageEventHandler MessageFinished;

		public string Text {
			get {
				return Data[0].ToLower();
			}
			set {
				if (Data == null || Data.Length < 1) {
					Data = new string[1];
				}
				Data[0] = value;
			}
		}

		/// <summary>
		/// Message data. 
		/// <para>Data[0] is the message text.</para>
		/// <para>Data[1-n] are arguments for the message.</para>
		/// </summary>
		protected string[] Data;

		/// <summary>
		/// Get the message arguments.
		/// </summary>
		/// <param name="index">Argument number</param>
		/// <returns></returns>
		public string this[int index] {
			get {
				if (Data == null)
					return "";
				else if (index >= Data.Length)
					return "";
				else if (index < 0)
					return "";
				else
					return Data[index];
			}
		}

		public int Count {
			get {
				if (Data == null)
					return 0;
				else
					return Data.Length;
			}
		}

		public bool Handled { get; set; }

		/// <summary>
		/// Init the message with the Message MessageData and optional arguments. 
		/// The message can be a semicolon delimited string (showmenu;mainmenu),
		/// an array of strings ("showmenu","mainmenu") or sent in as multiple parameters.
		/// </summary>
		/// <param name="MessageData"></param>
		/// <param name="Data"></param>
		public TVSMessage(params string[] MessageData) {
			if (MessageData.Length == 1)
				this.Data = MessageData[0].Split(';');
			else
				this.Data = MessageData;
		}

		public static void RegisterPlugin(IPlugin NewPlugin) {
			Plugins.Add(NewPlugin);
		}

		public static void RemovePlugin(IPlugin Plugin) {
			Plugins.Remove(Plugin);
		}

		public void Send() {
			this.Handled = false;
			Process();
		}

		private void Process() {
			for (int i = 0; i < Plugins.Count && !Handled; i++) {
				IPlugin p = Plugins[i];
				p.ProcessMessage(this);
			}
			if (MessageFinished != null)
				MessageFinished(this);
		}

		public static void Send(params string[] Text) {
			TVSMessage e = new TVSMessage(Text);
			e.Send();
		}


	}
}
